﻿
using System.IO;
using SuperGo.SilverlightLib.History;

namespace SuperGo.SilverlightLib.Sgf {
    public class SgfWriter {
        private static ISystem _system = new DefaultSystem();
        public const string APP_NAME = "superGo";
        public const string APP_VERSION = "1.0";

        private TextWriter Writer { get; set; }

        public SgfWriter(TextWriter writer) {
            Writer = writer;
        }

        public void Write(GoGame game) {
            Writer.WriteLine("(;GM[1]FF[4]AP[{0}:{1}]ST[1]", APP_NAME, APP_VERSION);
            Writer.WriteLine("");
            Writer.WriteLine("SZ[{0}]KM[0.0]", game.Board.Size);
            Writer.WriteLine("PW[{0}]PB[{1}]DT[{2}]", game.WhitePlayer.Name, game.BlackPlayer.Name, _system.GetCurrentDateTime().ToString("yyyy-MM-dd"));
            Writer.WriteLine("");
            foreach (HistoryEvent historyEvent in game.History.EventFromFirstToLast()) {
                if (historyEvent is PassHistoryEvent) {
                    PassHistoryEvent passHistoryEvent = (PassHistoryEvent)historyEvent;
                    Writer.WriteLine(";{0}[tt]", ToSgfColor(passHistoryEvent.Player));
                } else if (historyEvent is MoveHistoryEvent) {
                    MoveHistoryEvent moveHistoryEvent = (MoveHistoryEvent)historyEvent;
                    Writer.WriteLine(";{0}[{1}]", ToSgfColor(moveHistoryEvent.Player), ToSgfMove(moveHistoryEvent.X, moveHistoryEvent.Y));
                }
            }
            // ;B[bb]
            Writer.WriteLine(")");
        }

        private string ToSgfMove(int x, int y) {
            char charX = (char)('a' + x);
            char charY = (char)('a' + y);
            return string.Format("{0}{1}", charX, charY);
        }

        private string ToSgfColor(Player player) {
            return player.ToStoneState() == StoneState.Black ? "B" : "W";
        }

        public void Close() {
            Flush();
            Writer.Close();
        }

        public void Flush() {
            Writer.Flush();
        }

        public static ISystem System {
            set { _system = value; }
        }
    }
}
